package br.com.async.core.application.impl;

import java.util.List;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import br.com.async.core.application.CustomerApplication;
import br.com.async.core.domain.customer.Customer;
import br.com.async.core.domain.customer.CustomerRepository;
import br.com.async.core.domain.user.User;
import br.com.async.core.domain.user.UserRepository;
import br.com.async.core.util.Encrypt;

@Transactional(propagation = Propagation.REQUIRED)
public class CustomerApplicationImpl implements CustomerApplication {

	private CustomerRepository customerRepository;
	private UserRepository userRepository;

	public CustomerApplicationImpl(CustomerRepository customerRepository,
			UserRepository userRepository) {
		super();
		this.customerRepository = customerRepository;
		this.userRepository = userRepository;
	}

	@Override
	public void save(Customer entity) {

		customerRepository.save(entity);
		try {
			
		userRepository.save(
				new User(entity.getPerson().getContact().getEmail(), 
						Encrypt.md5(entity.getPerson().getContact().getEmail()
						+ " " + entity.getCpf()), entity.getPerson()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Override
	public void save(Customer entity, String password) {

		customerRepository.save(entity);
		try {
			
		userRepository.save(
				new User(entity.getPerson().getContact().getEmail(), 
						Encrypt.md5(entity.getPerson().getContact().getEmail()
						+ " " + password), entity.getPerson()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void update(Customer entity) {
		customerRepository.update(entity);
	}

	@Override
	public void disable(Customer entity) {
		customerRepository.disable(entity);
	}

	@Override
	public Customer findById(Integer code) {
		return customerRepository.findById(code);
	}

	@Override
	public List<Customer> list() {
		return customerRepository.list();
	}
	
	public Customer findCustomerByPersonCode(Integer personCode){
		return customerRepository.findCustomerByPersonCode(personCode);
	}

}
